package com.youdianstar.app.ui

import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.youdianstar.app.entity.RentCheck

import com.youdianstar.app.support.ApiRepository
import com.youdianstar.app.common.base.BaseViewModel
import com.youdianstar.app.common.event.NetStateLiveData
import com.youdianstar.app.common.event.SingleLiveEvent
import com.youdianstar.app.entity.RentResult
import com.youdianstar.app.entity.RentalAuthRequest
import com.youdianstar.app.entity.RentalAuthRes
import com.youdianstar.app.entity.ReqStationPlan
import com.youdianstar.app.entity.WalletInfo

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch


/**
 * File: ScanViewModel
 * Author: 82149 Create: 2021/10/26 18:51
 * Changes (from 2021/10/26)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class ScanViewModel(private val repo: ApiRepository) : BaseViewModel()  {
    //val anyLiveData = NetStateLiveData<Any>()

    val snoObField = ObservableField<String>("")
    val planNetDataFiled = ObservableField<ReqStationPlan>()

    // 标记租借下单状态
    var isReqRuler = false
    val planResultLiveData = NetStateLiveData<ReqStationPlan>()

    /**
     * 获取计费规则
     * @param sno 机柜编号
     * @param qrContent 二维码内容
     */
    fun getPricePlan(sno: String,qrContent: String){
        if (isReqRuler)
            return
        isReqRuler = true
        showLoading()
        viewModelScope.launch (Dispatchers.IO){
            repo.requestStationPlan(sno,qrContent,planResultLiveData)
        }
    }

    val rentCheckResultData = NetStateLiveData<RentCheck>()
    /**
     * 判断是否可以扫码
     *
     * @param sno 机柜编号
     */
    fun checkRentOrNot(sno: String){
        showLoading()
        viewModelScope.launch (Dispatchers.IO){
            repo.checkRentOrNot(sno,rentCheckResultData)
        }
    }


    val rentResultLiveData = NetStateLiveData<RentResult>()
    /**
     * 租借下单
     * @param sno 机柜编号
     */
    fun rentOrder(sno: String){
        showLoading()
        viewModelScope.launch (Dispatchers.IO){
            repo.rentOrder(sno,rentResultLiveData)
        }
    }

    val rentAuthResultLiveData = NetStateLiveData<RentalAuthRes>()
    /**
     * 租借下单 - 预授权
     * --合并业务接口,查两次(1.判断身份与授权状态 2.传入rentType授权租借)
     * @param req 机柜编号与Stripe method id
     */
    fun rentOrderPreAuth(req: RentalAuthRequest){
        showLoading()
        viewModelScope.launch (Dispatchers.IO){
            repo.rentOrderPreAuth(req,rentAuthResultLiveData)
        }
    }

    val walletNetLiveData = NetStateLiveData<WalletInfo>()

    /**
     * 获取钱包信息
     * @param isShow 展示
     */
    fun getWallet(isShow: Boolean) {
        if (isShow)
            showLoading()
        viewModelScope.launch(Dispatchers.IO) {
            repo.getWallet(walletNetLiveData)
        }
    }

    /*****************************进度条页面-租借下单*******************************/

    val queryResultLiveData = NetStateLiveData<RentResult>()

    fun queryRentResult(orderNo :String){
        viewModelScope.launch (Dispatchers.IO){
            repo.queryRentResult(orderNo,queryResultLiveData)
        }
    }

    val timeCountEvent = SingleLiveEvent<Int>()
    var countJob : Job? =null

    /*计时功能*/
    fun countTime(){
        countJob = flow{
            for (i in 0..60){
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion {
               // timeCountEvent.value = -1 //countJob cancel 会走这里
            }
            .onEach {
                timeCountEvent.value = it
            }
            .flowOn(Dispatchers.Main)
            .launchIn(viewModelScope)
    }

    val finishCountEvent = SingleLiveEvent<Int>()
    var finishJob : Job? =null

    /*计时功能*/
    fun finishCountTime(){
        finishJob = flow{
            for (i in 0..5){
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion {
                // timeCountEvent.value = -1 //countJob cancel 会走这里
            }
            .onEach {
                finishCountEvent.value = (5-it)
            }
            .flowOn(Dispatchers.Main)
            .launchIn(viewModelScope)
    }

    /*******************************充电卡扫码********************************/

    var rewardQRType = 0
    val redeemChargingCardResultData = NetStateLiveData<Any>()
    /**
     * 充电卡扫码-兑换
     *
     * @param code 码
     */
    fun redeemRewardCode(type:Int,code:String){
        showLoading()
        rewardQRType = type
        viewModelScope.launch(Dispatchers.IO) {
            repo.scanRewardCode(type, code,redeemChargingCardResultData)
        }
    }

    /*******************************扫码结果*******************************/

    val scanResultLiveData = NetStateLiveData<Any>()
    /**
     * 查询机柜信息 - 扫码结果
     * @param deviceId 设备ID
     */
    fun getScanResult(deviceId: String) {
        showLoading()
        viewModelScope.launch(Dispatchers.IO) {
            repo.getScanResult(deviceId, scanResultLiveData)
        }
    }

}